<template>
  <div class="select-wrapper">
    <label for="paymentOptions">请选择支付方式：</label>
    <select id="paymentOptions"  v-model="selectedValue" @change="onChange">
      <option v-for="option in paymentOptions" :key="option.id" :value="option">
        {{ option.addressArea + ' - ' + option.addressDetail + ' - ' + option.addressPhone + ' - ' + option.addressLinkman }}
      </option>
    </select>
  </div>
</template>

<script>import { BASE_URL } from "@/util/Config.js";
import { useUserStore } from '@/stores/user';

export default {
  props: {
    modelValue: {
      type: [String, Number],
      default: null
    }
  },  // 替代原来的 value
  emits: ['update:modelValue', 'change'],
  data() {
    return {
      selectedValue: this.modelValue,
      paymentOptions: []
    };
  },
  watch: {
    modelValue(newVal) {
      this.selectedValue = newVal;
    },
    selectedValue(newVal) {
      this.$emit('update:modelValue', newVal);
    }
  },
  methods: {
    async fetchPaymentOptions() {
      const userStore = useUserStore();
      const userId = userStore.userInfo?.userId;
      try {
        const response = await fetch(BASE_URL + '/my/addresses', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ userId })
        });

        if (!response.ok) throw new Error('请求失败');
        const data = await response.json();
        this.paymentOptions = data.data;
      } catch (error) {
        console.error('获取地址失败:', error);
        alert('加载地址失败，请刷新页面重试');
      }
    },
    onChange(event) {
      const selectedOption = this.paymentOptions.find(option => option.id === parseInt(event.target.value));
      if (selectedOption) {
        this.selectedValue = selectedOption;
        this.$emit('update:modelValue', selectedOption); // 传递整个对象
      }
    }
  },
  mounted() {
    this.fetchPaymentOptions();
  }
};
</script>


<style scoped>.select-wrapper {
  max-width: 300px;
  margin: 20px auto;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

select {
  width: 100%;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  height: auto; /* 根据内容自动调整高度 */
}

p {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
}
</style>